package user

import (
	"context"
	"strconv"

	"mall/service/backend/api/internal/logic/user/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/logic/utils/parse"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetUserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取User列表
func NewBackendGetUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetUserListLogic {
	return &BackendGetUserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BackendGetUserListLogic) BackendGetUserList(req *types.UserListReq) (resp *types.UserListResp, err error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)

	data, err := l.svcCtx.UserRpc.BackendGetUserList(l.ctx, &userclient.UserListReq{
		Page:     page,
		PageSize: pageSize,
		UserId:   req.UserId,
		Mobile:   req.Mobile,
		OrderBy:  orderBys,
		FilterBy: filterBys,
	})
	if err != nil {
		return
	}

	resp = &types.UserListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.UserListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
		},
	}

	for _, v := range data.List {
		option := utils.GetOptionByStatus(v.Status)
		ss, _ := strconv.Atoi(*v.Id)
		resp.Data.List = append(resp.Data.List, &types.UserInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         pointy.GetPointer(uint64(ss)),
				CreatedAt:  v.CreatedAt,
				UpdatedAt:  v.UpdatedAt,
				DeletedAt:  v.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Username:         v.Username,
			Email:            v.Email,
			Mobile:           v.Mobile,
			Status:           v.Status,
			LastLoginTime:    v.LastLoginTime,
			EmailVerified:    v.EmailVerified,
			EmailVerifiedAt:  v.EmailVerifiedAt,
			MobileVerified:   v.MobileVerified,
			MobileVerifiedAt: v.MobileVerifiedAt,
			CreatedIP:        v.CreatedIP,
			IsSystem:         v.IsSystem,
			//Password:         v.Password,
		})
	}

	return resp, nil
}
